<?php
/**
 * 小区模型
 */

namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\TencentMap;
use map\BaiDu;
use oss\Oss;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class HouseVillage extends BaseModel {

    public static $source_type = [
        1 => '安居客',
        2 => '后台添加',
    ];

    /**
     * 小区列表
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function vallige_list($params, &$page, &$pageNum, &$data, &$count) {
        $city_code = $params['city_code'];
        //默认当前区域
        $p_codes = db('region')
            ->where('city_code', $city_code)
            ->where('rank', 2)
            ->value('p_codes');
        $city_codes = $p_codes . $city_code . ',';
        $map = [];
        $map[] = ['hv.city_codes', 'like', $city_codes . '%'];
        if (!empty($params['vname'])) {
            $map[] = ['hv.name', 'like', '%' . trim($params['vname']) . '%'];
        }
        $whereRaw = '';
        if (!empty($params['type']) && $params['type'] == 'hot') {
            $whereRaw = 'hot.id is not null';
        }
        $column = ['hv.id', 'hv.name', 'hv.area as a_name', 'hv.city as c_name', 'hv.province  as p_name', 'hv.price_unit_avg', 'if(hot.id is not null,1,0 ) as is_hot', 'hv.cover', 'hv.address as address', 'hv.total_num', 'hv.sale_num','hv.source_url','hv.source_type'];
        $orderby = ['hv.id' => 'desc'];
        empty($params['page']) ? $start = 1 : $start = $params['page'];
        empty($params['long']) ? $long = 12 : $long = $params['long'];
        self::sql_list($map, $column, $start, $long, $orderby, $whereRaw, '', $page, $pageNum, $data, $count);
    }

    /**
     * 小区列表sql
     * @param $map
     * @param $column
     * @param $start
     * @param $long
     * @param $orderby
     * @param $orderRaw
     * @param $page
     * @param $pageNum
     * @param $data
     * @param $count
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function sql_list($map, $column, $start, $long, $orderby, $whereRaw, $orderRaw, &$page, &$pageNum, &$data, &$count) {
        $sql = db("house_village")
            ->alias('hv')
            ->leftJoin('hot_vallige hot', 'hot.village_id=hv.id')
            ->where($map);
        if ($whereRaw) {
            $sql->whereRaw($whereRaw);
        }
        $sql->field($column)
            ->order($orderby);
        if ($orderRaw) {
            $sql->orderRaw("field(hv.id,{$orderRaw})");
        }
        $data = $sql->page($start, $long)
            ->select();

        $page = $start;

        $count_ = db("house_village")
            ->alias('hv')
            ->leftJoin('hot_vallige hot', 'hot.village_id=hv.id')
            ->where($map);
        if ($whereRaw) {
            $count_->whereRaw($whereRaw);
        }
        $count = $count_->count();
        foreach ($data as $k => $datum) {
            $data[$k]['address'] = $datum['p_name'] . '-' . $datum['c_name'] . '-' . $datum['a_name'];
            unset($data[$k]['a_name']);
            unset($data[$k]['c_name']);
            unset($data[$k]['p_name']);
            $data[$k]['end_num'] = $datum['total_num'] - $datum['sale_num'];
            $data[$k]['source_type'] = self::$source_type[$datum['source_type']];
            $data[$k]['source_url'] = $datum['source_url'];
        }
        if ($long > 0) {
            $pageNum = ceil($count / $long);
        } else {
            $pageNum = 1;
        }
    }

    /**
     * 筛选多条
     * @param array|null $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas(?array $map, $column) {
        return db('house_village')
            ->where($map)
            ->field($column)
            ->select();
    }

    /**
     * 小区详情
     * @param $params
     * @param $data
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getInfo($params) {
        $data = db('house_village')
            ->field('property,cost,acreage,person_num,years,parking_space,plot_ratio,greening_rate,related_school,business_name,developers,tenement,name,address,price_unit_avg,cover,x(location) as lng,Y(location) as lat,province,city,area')
            ->find($params['id']);
        if (empty($data)) {
            Err::add('数据不存在', RespCode::DATA_ERR);
            return false;
        }
        $data['cover'] = empty($data['cover']) ? config('global.empty_house_img') : $data['cover'];
        $data['acreage'] = empty($data['acreage']) ? '' : $data['acreage'];
        return $data;
    }

    /**
     * 删除
     * @param $params
     * @return bool
     * @throws Exception
     * @throws PDOException
     */
    public static function del($params) {
        Db::startTrans();
        $p_codes = Db::name('region')->where('city_code', $params['city_code'])->value('p_codes');
        $codes = $p_codes . $params['city_code'] . ',';
        $data1 = Db::name('house_village')
            ->where('id', $params['id'])
            ->where('city_code', 'like', $codes . '%')
            ->find();
        if (empty($data1)) {
            Err::add('数据不存在');
            return false;
        }
        $data2 = House::where('village_id', $params['id'])->select()->toArray();
        if ($data2) {
            Err::add('该小区有关联房源');
            return false;
        }
        if (!self::where('id', $params['id'])->delete()) {
            Db::rollback();
            Err::add('删除失败');
            return false;
        }
        if (HotVallige::where('village_id', $params['id'])->select()->toArray()) {
            if (!HotVallige::del($params['id'])) {
                Db::rollback();
                Err::add('删除失败');
                return false;
            }
        }
        Db::commit();
        return true;
    }

    /**
     * 筛选单条
     * @param array|null $map
     * @param $column
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne(?array $map, $column) {
        return Db::name('house_village')
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 房源详情补录信息编辑-区下面的小区
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getBusvillage($params): array {
        $house = House::getOne([['id', '=', $params['id']]], 'city_codes');
        $city_codes = explode(',', $house['city_codes']);
        if (!empty($city_codes[3])) {
            $data = Db::name('house_village')
                ->where('city_code', $city_codes[3])
                ->field('name,id')
                ->select();
            foreach ($data as $k => $v) {
                $data[$k]['rank'] = 5;
            }
            return $data;
        } else {
            return [];
        }
    }

    /**
     * 小区新增/编辑 表单验证
     * @param $params
     * @return bool
     */
    public static function checkParams(&$params) {
        if (mb_strlen(trim($params['name']), 'utf-8') > 50) {
            Err::add('小区名称长度限制50', RespCode::PARAMS_ERR);
            return false;
        }
        if (mb_strlen(trim($params['address']), 'utf-8') > 100) {
            Err::add('地址长度限制100', RespCode::PARAMS_ERR);
            return false;
        }
        if (!empty($params['price_unit_avg'])) {
            if (preg_match('/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{0,2})?$/', $params['price_unit_avg']) == false) {
                Err::add('均价请输入1-9999999999的小数，最多两位小数', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['source_url'])) {
            if (mb_strlen(trim($params['source_url']), 'utf-8') > 100) {
                Err::add('来源网站长度限制100', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['summary'])) {
            if (mb_strlen(trim($params['summary']), 'utf-8') > 100) {
                Err::add('小区概况长度限制100', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['property'])) {
            if (mb_strlen(trim($params['property']), 'utf-8') > 50) {
                Err::add('建筑类型长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['cost'])) {
            if (mb_strlen(trim($params['cost']), 'utf-8') > 50) {
                Err::add('物业费长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['total_build'])) {
            if (mb_strlen(trim($params['total_build']), 'utf-8') > 50) {
                Err::add('总栋数长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['person_num'])) {
            if (mb_strlen(trim($params['person_num']), 'utf-8') > 50) {
                Err::add('总户数长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['years'])) {
            if (mb_strlen(trim($params['years']), 'utf-8') > 50) {
                Err::add('建筑年代长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['parking_space'])) {
            if (mb_strlen(trim($params['parking_space']), 'utf-8') > 50) {
                Err::add('停车位长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['plot_ratio'])) {
            if (mb_strlen(trim($params['plot_ratio']), 'utf-8') > 50) {
                Err::add('容积率长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['greening_rate'])) {
            if (mb_strlen(trim($params['greening_rate']), 'utf-8') > 50) {
                Err::add('绿化长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['developers'])) {
            if (mb_strlen(trim($params['developers']), 'utf-8') > 50) {
                Err::add('开发商长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['tenement'])) {
            if (mb_strlen(trim($params['tenement']), 'utf-8') > 50) {
                Err::add('物业公司长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['trading_ownership'])) {
            if (mb_strlen(trim($params['trading_ownership']), 'utf-8') > 50) {
                Err::add('交易权属长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['electricity_type'])) {
            if (mb_strlen(trim($params['electricity_type']), 'utf-8') > 50) {
                Err::add('用电类型长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['water_type'])) {
            if (mb_strlen(trim($params['water_type']), 'utf-8') > 50) {
                Err::add('用水类型长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['heating_type'])) {
            if (mb_strlen(trim($params['heating_type']), 'utf-8') > 50) {
                Err::add('供暖类型长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['gas_fee'])) {
            if (mb_strlen(trim($params['gas_fee']), 'utf-8') > 50) {
                Err::add('燃气费用长度限制50', RespCode::PARAMS_ERR);
                return false;
            }
        }
        return true;
    }

    /**
     * 编辑
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function edit($params) {
        if (!empty($params['id'])) {
            $old = db('house_village')
                ->where('id', $params['id'])
                ->find();
            if (empty($old)) {
                Err::add('小区不存在', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!self::checkParams($params)) {
            return false;
        }

        $region = Region::where('city_code', $params['area_code'])->find();
        if ($region['p_code'] != $params['city_code']) {
            Err::add('区域code参数错误', RespCode::PARAMS_ERR);
            return false;
        }
        $codes = $region['p_codes'] . $region['city_code'] . ',';
        $_codes = explode(',', $codes);
        $hvName = replaceSpecialChar(trim($params['name']));

        $b_id = $params['b_id'] ?? 0;

        if ($b_id != 0 && empty(db::name('business_area')
                ->where('city_id', $params['area_code'])
                ->where('id', $b_id)
                ->select())) {
            Err::add('商圈参数错误', RespCode::PARAMS_ERR);
            return false;
        }

        $data = [
            'business_area'     => $b_id,
            'name'              => $hvName,
            'cover'             => empty($params['cover']) ? '' : $params['cover'],
            'address'           => trim($params['address']),
            'price_unit_avg'    => empty($params['price_unit_avg']) ? '' : $params['price_unit_avg'],
            'summary'           => empty($params['summary']) ? '' : trim($params['summary']),
            'property'          => empty($params['property']) ? '' : trim($params['property']),
            'cost'              => empty($params['cost']) ? '' : trim($params['cost']),
            'years'             => empty($params['years']) ? '' : trim($params['years']),
            'parking_space'     => empty($params['parking_space']) ? '' : trim($params['parking_space']),
            'plot_ratio'        => empty($params['plot_ratio']) ? '' : trim($params['plot_ratio']),
            'greening_rate'     => empty($params['greening_rate']) ? '' : trim($params['greening_rate']),
            'tenement'          => empty($params['tenement']) ? '' : trim($params['tenement']),
            'location'          => Db::raw("POINT('{$params['lng']}', '{$params['lat']}')"),
            'lat'               => $params['lat'],
            'lng'               => $params['lng'],
            'source_url'        => empty($params['source_url']) ? '' : trim($params['source_url']),
            'person_num'        => empty($params['person_num']) ? '' : trim($params['person_num']),
            'developers'        => empty($params['developers']) ? '' : trim($params['developers']),
            'city_code'         => $params['area_code'],
            'total_build'       => empty($params['total_build']) ? '' : trim($params['total_build']),
            'city_codes'        => $codes,
            'area'              => $region['name'],
            'province'          => Region::where('city_code', $_codes[1])->value('name'),
            'city'              => Region::where('city_code', $_codes[2])->value('name'),
            'business_name'     => isset($params['b_id']) && $params['b_id'] != 0 ? BusinessArea::where('id', $params['b_id'])->value('name') : '',
            'trading_ownership' => empty($params['trading_ownership']) ? '' : trim($params['trading_ownership']),
            'electricity_type'  => empty($params['electricity_type']) ? '' : trim($params['electricity_type']),
            'water_type'        => empty($params['water_type']) ? '' : trim($params['water_type']),
            'heating_type'      => empty($params['heating_type']) ? '' : trim($params['heating_type']),
            'gas_fee'           => empty($params['gas_fee']) ? '' : trim($params['gas_fee']),
            'itime'             => time(),
            'day_itime'         => strtotime(date('Y-m-d', time())),
            'month_itime'       => strtotime(date('Y-m', time())),

            //            'tx_lng'      => $ret['locations'][0]['lng'],
            //            'tx_lat'      => $ret['locations'][0]['lat'],
            //            'tx_location' => Db::raw("POINT('{$ret['locations'][0]['lng']}', '{$ret['locations'][0]['lat']}')"),
        ];
        $exists = db("house_village")
            ->where('name', $hvName)
            ->where('city_codes', 'like', $region['p_codes'] . '%')
            ->find();
        //添加
        if (empty($params['id'])) {
            if ($exists) {
                Err::add('已存在该小区，若确定为重名小区，请更换小区名称再次提交');
                return false;
            }
            self::insert($data);
        } else {//编辑
            //删除图片
            if ($old['cover'] != $params['cover'] && !empty($old['cover'])) {
                $oss = Oss::getInstance();
                $oss->delOneFile($old['cover']);
            }
            $oldName = db('house_village')->where("id", $params['id'])->value('name');
            if ($oldName != $hvName) {
                if ($exists) {
                    Err::add('已存在该小区，若确定为重名小区，请更换小区名称再次提交');
                    return false;
                }
            }
            self::where('id', $params['id'])->update($data);
        }
        return true;
    }

    /**
     * 名称匹配小区
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function searchName($params) {
        $city_code = $params['city_code'];
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        return db('house_village')
            ->where("name", 'like', '%' . trim($params['name']) . '%')
            ->where('city_codes', 'like', trim($codes) . '%')
            ->field('name,id')
            ->limit(10)
            ->select();
    }

    /**
     * 房源补录选择小区
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function selectHvId($params) {
        $house_village = db('house_village')
            ->where('id', $params['id'])
            ->field('city_codes,business_area,address,lng,lat')
            ->find();
        $city_code = explode(',', $house_village['city_codes']);
        $city_name = Region::getOne([['city_code', '=', $city_code[2]]], 'name,city_code');
        $area = Region::getOne([['city_code', '=', $city_code[3]]], 'name,city_code');
        $business_area = BusinessArea::getOne([['id', '=', $house_village['business_area']]], 'name,id');
        $info['city'] = $city_name;
        $info['area'] = $area;
        $info['business_area'] = $business_area;
        $info['lat'] = $house_village['lat'];
        $info['lng'] = $house_village['lng'];
        $info['address'] = $house_village['address'];
        return $info;
    }


}
